//
//  FoundBluetoothVC.m
//  PStoneSDKDemo
//
//  Created by 元潮 谢 on 16/10/8.
//  Copyright © 2016年 元潮 谢. All rights reserved.
//

#import "FoundBluetoothVC.h"
#import "FoundBluetoothVCCell.h"
#import "ProgressHUD.h"
#import "SettingUtils.h"
#import "LMFlatformSDK.h"
#import "Utils.h"
#import "SigninVC.h"
#import "LockBlueTooth.h"

@interface FoundBluetoothVC ()
{
    
    NSMutableArray * mLockArray;
    
    NSMutableArray * peripheralsNotSetPs;
//    NSMutableArray * peripheralsSetPs;
    CBPeripheral * currentPeripheral;
    NSDictionary* currentAdvData;
    
    BlueToothSDK *blueToothSDK;
    
    NSString * mLockNameInput;
    
    NSString * mConnectUnlockMacAddress;
    BOOL unlockWithMacAddress;
    
}


@end


@implementation FoundBluetoothVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        //右边按钮
        UIBarButtonItem * addDongTai = [[UIBarButtonItem alloc]initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(scanAction:)];
        self.navigationItem.rightBarButtonItem = addDongTai;
        
        self.navigationItem.hidesBackButton = YES;
        
        UIBarButtonItem * leftButton = [[UIBarButtonItem alloc]initWithTitle:@"切换账户" style:UIBarButtonItemStylePlain target:self action:@selector(quit:)];
        self.navigationItem.leftBarButtonItem = leftButton;
        
        self.title = [NSString stringWithFormat:@"设备(%@)",[SettingUtils getAccount]];
    }
    
    return self;
}

-(void)quit:(id)sender
{
    for (UIViewController * vc in self.navigationController.viewControllers) {
        
        if ([vc isKindOfClass:[SigninVC class]]) {
            
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
    }
    SigninVC * vc = [[SigninVC alloc]initWithNibName:@"SigninVC" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)scanAction:(id)sender
{

    [peripheralsNotSetPs removeAllObjects];
//    [peripheralsSetPs removeAllObjects];
    [self.tableView reloadData];
    [blueToothSDK scan];
    
//    self.navigationItem.rightBarButtonItem = nil;
    
    
//    [ProgressHUD show:@"正在绑定..."];
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
//    dispatch_async(queue, ^(void){
//        
//        __block NSDictionary* responseDictionary;
//        dispatch_sync(queue, ^(void){
//            
//            
//            LMFlatformSDK * netSDK = [[LMFlatformSDK alloc]initWithCompanyID:@"1001"];
////            responseDictionary = [netSDK bindManagerUserID:@"0001" lockMacAddress:@"6C:EC:EB:52:C8:B8"];
//            
//            
//            responseDictionary = [netSDK requestLockKeyUserId:@"0001" type:2 lockMacAddress:@"6C:EC:EB:52:C8:B8"];
//            
//        });
//        
//        dispatch_sync(dispatch_get_main_queue(), ^(void){
//            
//            if (responseDictionary) {
//                
//                NSNumber * code = (NSNumber*)[responseDictionary valueForKey:@"code"];
//                NSLog(@"code:%@",code);
//                if (code && code.intValue == 0) {
//                    
//                    //获取数据成功
//                    
//                    NSDictionary * data = (NSDictionary*)[responseDictionary valueForKey:@"data"];
//                    
//                    [SettingUtils setAESKey:[data valueForKey:@"key"] lockName:[currentAdvData objectForKey:@"kCBAdvDataLocalName"]];
//                    
//                    NSLog(@"key:%@",[data valueForKey:@"key"]);
//                    
//                    [ProgressHUD dismiss];
//                    
//                }else{
//                    
//                    NSLog(@"绑定失败1");
//                    [ProgressHUD dismiss];
//                    
//                    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"绑定失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
//                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//                        
//                    }];
//                    [alertController addAction:cancelAction];
//                    [self presentViewController:alertController animated:YES completion:nil];
//                    
//                }
//                
//            }else{
//                
//                NSLog(@"绑定失败");
//                [ProgressHUD dismiss];
//                
//                
//                UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"绑定失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
//                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//                    
//                }];
//                [alertController addAction:cancelAction];
//                [self presentViewController:alertController animated:YES completion:nil];
//            }
//            
//            
//        });
//        
//    });

    
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    mLockArray  = [[NSMutableArray alloc]init];
    peripheralsNotSetPs = [[NSMutableArray alloc]init];
//    peripheralsSetPs = [[NSMutableArray alloc]init];
    
    //初始化
    blueToothSDK = [[BlueToothSDK alloc] init];
    blueToothSDK.delegate = self;
    [blueToothSDK setupBlueTooth];
    
    //搜索附近蓝牙
//    [blueToothSDK scan];
    
}

-(void)viewWillAppear:(BOOL)animated
{

    [super viewWillAppear:animated];
    
    
    self.title = [NSString stringWithFormat:@"设备(%@)",[SettingUtils getAccount]];
    [peripheralsNotSetPs removeAllObjects];
//    [peripheralsSetPs removeAllObjects];
    [self getData];
}

-(void)getData{
    
    [mLockArray removeAllObjects];
    [self.tableView reloadData];
    [ProgressHUD show:@"获取数据"];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
    dispatch_async(queue, ^(void){
        
        __block BOOL success = NO;
//        __block NSDictionary* responseDictionary;
        dispatch_sync(queue, ^(void){
            
            LMFlatformSDK * netSDK = [[LMFlatformSDK alloc]initWithCompanyID:@"1001"];
            NSDictionary * responseDictionaryLocks = [netSDK requestLocksWithUserID:[SettingUtils getAccount] type:1];
            
            
            if (responseDictionaryLocks) {
                
                NSNumber * code = (NSNumber*)[responseDictionaryLocks valueForKey:@"code"];
                
                if (code && code.intValue == 0) {
                    
                    //获取数据成功
                    NSArray * data = (NSArray*)[responseDictionaryLocks valueForKey:@"data"];
                    if (![data isKindOfClass:[NSNull class]]) {
                        
                        for (NSDictionary * dict in data) {
                            
                            LockBlueTooth * lock = [[LockBlueTooth alloc]initWithMacAddress:[dict valueForKey:@"lockMac"] lockName:[dict valueForKey:@"lockName"]];
                            [mLockArray addObject:lock];
                            
                            //获取key
                            NSDictionary *responseDictionary = [netSDK requestLockKeyUserId:[SettingUtils getAccount] type:1 lockMacAddress:lock.macAddress];
                            
                            NSNumber * code = (NSNumber*)[responseDictionary valueForKey:@"code"];
                            if (code && code.intValue == 0) {
                                
                                //获取数据成功
                                NSDictionary * data = (NSDictionary*)[responseDictionary valueForKey:@"data"];
                                
                                [SettingUtils setAESKey:[data valueForKey:@"key"] lockName:lock.macAddress];
                                
                            }
                            
                        }
                        
                    }
                    
                    success = YES;
                    
                }
                
            }
            
        });
        
        dispatch_sync(dispatch_get_main_queue(), ^(void){
            
            [ProgressHUD dismiss];
            
            if (success) {
                
                [self.tableView reloadData];
                
            }else{
                
                UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"获取服务器锁列表失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
                
            }
            
        });
        
    });

}

-(void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    
//    delegate.blueToothSDK.delegate = delegate;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        
        //搜索到的蓝牙设备
        
        if (peripheralsNotSetPs) {
            
            return  peripheralsNotSetPs.count;
        }else{
            
//            return peripheralsSetPs.count;
            return 0;
        }
    }else if(section == 1){
    
        return 0;
    }else {
        
        //服务器获取到的数据
        return mLockArray.count;
    }
    
}

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{

    if (section == 0) {
        
        return @"搜索到的未设置密钥的锁";
    }else if(section == 1){
    
//        return @"搜索到的已设置密钥的锁";
        return @"";
    }else {
    
        return [NSString stringWithFormat:@"名下已绑定的锁（%lu个）",(unsigned long)mLockArray.count];
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"FoundBluetoothVCCell";
    FoundBluetoothVCCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (!cell) {
        
        cell = [[[NSBundle mainBundle] loadNibNamed:@"FoundBluetoothVCCell"
                                              owner:self
                                            options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        
    }
    
    if (indexPath.section == 2) {
        LockBlueTooth * lock = [mLockArray objectAtIndex:indexPath.row];
        cell.label1.text = [NSString stringWithFormat:@"%@［%@］",lock.lockName,lock.macAddress];
        
    }else if(indexPath.section == 1){
        
//        //已绑定
//        CBPeripheral * p = [((NSDictionary*)[peripheralsSetPs objectAtIndex:indexPath.row]) valueForKey:@"peripheral"];
//        
//        
//        if (p.state == CBPeripheralStateConnected) {
//            
//            [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
//            
//        }else{
//            
//            [cell setAccessoryType:UITableViewCellAccessoryNone];
//            
//        }
//        
//        //    d3010100 00000000 00000000
//        
//        NSMutableDictionary* dataTmp = [((NSMutableDictionary*)[peripheralsSetPs objectAtIndex:indexPath.row]) valueForKey:@"advertisementdata"];
//        
//        NSData * strProtocol = [dataTmp objectForKey:@"kCBAdvDataManufacturerData"];
//        Byte * bytes = strProtocol.bytes;
//        
//        
//        //    扫描回复数据的厂商自定义数据中包含锁控制模块是否已设置新秘钥的状态指示，如“07 ff d3 00” 中的 00 表示未设置新秘钥；“07 ff d3 01” 中的 01 表示已设置新秘钥。
//        
//        if (bytes[1]==0) {
//            
//            //没有设置密码
//            cell.label1.text = [NSString stringWithFormat:@"%@:%@ ( %0x:没有设置开锁密码，请先设置密码 )",[dataTmp objectForKey:@"kCBAdvDataLocalName"],[self getMacAddressFromAdvData:dataTmp], bytes[1]];
//            
//        }else if(bytes[1]==1){
//            
//            //已经设置密码，可以开锁
//            cell.label1.text = [NSString stringWithFormat:@"%@:%@ ( %0x:已设置开锁密码，可尝试开锁 )",[dataTmp objectForKey:@"kCBAdvDataLocalName"],[self getMacAddressFromAdvData:dataTmp],bytes[1]];
//        }
    }else {
        //未绑定
    
        CBPeripheral * p = [((NSDictionary*)[peripheralsNotSetPs objectAtIndex:indexPath.row]) valueForKey:@"peripheral"];
        
        
        if (p.state == CBPeripheralStateConnected) {
            
            [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
            
        }else{
            
            [cell setAccessoryType:UITableViewCellAccessoryNone];
            
        }
        
        //    d3010100 00000000 00000000
        
        NSMutableDictionary* dataTmp = [((NSMutableDictionary*)[peripheralsNotSetPs objectAtIndex:indexPath.row]) valueForKey:@"advertisementdata"];
        
        NSData * strProtocol = [dataTmp objectForKey:@"kCBAdvDataManufacturerData"];
        Byte * bytes = strProtocol.bytes;
        
        
        //    扫描回复数据的厂商自定义数据中包含锁控制模块是否已设置新秘钥的状态指示，如“07 ff d3 00” 中的 00 表示未设置新秘钥；“07 ff d3 01” 中的 01 表示已设置新秘钥。
        
        if (bytes[1]==0) {
            
            //没有设置密码
            cell.label1.text = [NSString stringWithFormat:@"%@:%@ ( %0x:没有设置开锁密码，请先设置密码 )",[dataTmp objectForKey:@"kCBAdvDataLocalName"],[self getMacAddressFromAdvData:dataTmp], bytes[1]];
            
        }else if(bytes[1]==1){
            
            //已经设置密码，可以开锁
            cell.label1.text = [NSString stringWithFormat:@"%@:%@ ( %0x:已设置开锁密码，可尝试开锁 )",[dataTmp objectForKey:@"kCBAdvDataLocalName"],[self getMacAddressFromAdvData:dataTmp],bytes[1]];
        }
    }
    
    return (UITableViewCell *) cell;
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 2 || indexPath.section == 1) {
        
        unlockWithMacAddress = YES;
        //网络的数据，修改昵称
        
        [ProgressHUD show:@"尝试开锁，请稍候..."];
        LockBlueTooth * lock = [mLockArray objectAtIndex:indexPath.row];
        
        [blueToothSDK unlockWithKey:[SettingUtils getAESKeylockName:lock.macAddress] macAddress:lock.macAddress connectTime:5.0f];
        
//        LockBlueTooth * lock = [mLockArray objectAtIndex:indexPath.row];
//        
//        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"修改锁名称。" message:nil preferredStyle:UIAlertControllerStyleAlert];
//        
//        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//            NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");
//            
//        }];
//        
//        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
//            
//            //身份认证
//            [ProgressHUD show:@"请稍候..."];
//            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
//            dispatch_async(queue, ^(void){
//                
//                __block NSDictionary* responseDictionary;
//                dispatch_sync(queue, ^(void){
//                    
//                    LMFlatformSDK * netSDK = [[LMFlatformSDK alloc]initWithCompanyID:@"1001"];
//                    responseDictionary = [netSDK modifyLockName:mLockNameInput UserID:[SettingUtils getAccount] type:1 lockMacAddress:lock.macAddress];
//                    
//                });
//                
//                dispatch_sync(dispatch_get_main_queue(), ^(void){
//                    
//                    [ProgressHUD dismiss];
//                    
//                    [self getData];
//                    
//                    if (responseDictionary) {
//                        
//                        NSNumber * code = (NSNumber*)[responseDictionary valueForKey:@"code"];
//                        
//                        if (code && code.intValue == 0) {
//                            
//                            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"修改锁名称成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
//                            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//                                
//                            }];
//                            [alertController addAction:cancelAction];
//                            [self presentViewController:alertController animated:YES completion:nil];
//                            
//                        }else{
//                            
//                            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"修改锁名称失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
//                            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//                                
//                            }];
//                            [alertController addAction:cancelAction];
//                            [self presentViewController:alertController animated:YES completion:nil];
//                        }
//                        
//                    }else {
//                        
//                        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"修改锁名称失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
//                        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//                            
//                        }];
//                        [alertController addAction:cancelAction];
//                        [self presentViewController:alertController animated:YES completion:nil];
//                    }
//                    
//                });
//                
//            });
//            
//            
//        }];
//        
//        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
//            // 可以在这里对textfield进行定制，例如改变背景色
//            
//            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];
//            
//            textField.text = lock.lockName;
//        }];
//        
//        
//        [alertController addAction:cancelAction];
//        [alertController addAction:okAction];
//        
//        [self presentViewController:alertController animated:YES completion:nil];

        
        return;
    
    }
    
    
//    CBPeripheral* peripheral;
//    if (indexPath.section == 1) {
//        
//        // 已绑定
////        CBPeripheral* peripheral = [((NSMutableDictionary*)[peripheralsSetPs objectAtIndex:indexPath.row]) valueForKey:@"peripheral"];
////        currentAdvData = [((NSMutableDictionary*)[peripheralsSetPs objectAtIndex:indexPath.row]) valueForKey:@"advertisementdata"];
//        
//    }else{
//    
//        // 未绑定
//        CBPeripheral* peripheral = [((NSMutableDictionary*)[peripheralsNotSetPs objectAtIndex:indexPath.row]) valueForKey:@"peripheral"];
//        currentAdvData = [((NSMutableDictionary*)[peripheralsNotSetPs objectAtIndex:indexPath.row]) valueForKey:@"advertisementdata"];
//        
//    }
        
    
    CBPeripheral* peripheral = [((NSMutableDictionary*)[peripheralsNotSetPs objectAtIndex:indexPath.row]) valueForKey:@"peripheral"];
    currentAdvData = [((NSMutableDictionary*)[peripheralsNotSetPs objectAtIndex:indexPath.row]) valueForKey:@"advertisementdata"];
    
    currentPeripheral = peripheral;
    
    //    扫描回复数据的厂商自定义数据中包含锁控制模块是否已设置新秘钥的状态指示，如“07 ff d3 00” 中的 00 表示未设置新秘钥；“07 ff d3 01” 中的 01 表示已设置新秘钥。
    
    NSData * strProtocol = [currentAdvData objectForKey:@"kCBAdvDataManufacturerData"];
    Byte * bytes = strProtocol.bytes;
    
    NSLog(@"didselect:%@,%i",currentAdvData,bytes[1]);
    if (bytes[1]==0) {
        
        //没有设置密码
        [ProgressHUD show:@"正在绑定..."];
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
        dispatch_async(queue, ^(void){
            
            __block NSDictionary* responseDictionary;
            dispatch_sync(queue, ^(void){
                
                
                LMFlatformSDK * netSDK = [[LMFlatformSDK alloc]initWithCompanyID:@"1001"];
                responseDictionary = [netSDK bindManagerUserID:[SettingUtils getAccount] lockMacAddress:[self getMacAddressFromAdvData:currentAdvData]];
                
            });
            
            dispatch_sync(dispatch_get_main_queue(), ^(void){
            
                if (responseDictionary) {
                    
                    NSNumber * code = (NSNumber*)[responseDictionary valueForKey:@"code"];
                    
                    if (code && code.intValue == 0) {
                        
                        //获取数据成功
                        
                        [self performSelector:@selector(connectTimeOut) withObject:nil afterDelay:10];
                        
                        NSDictionary * data = (NSDictionary*)[responseDictionary valueForKey:@"data"];
                        
                        [SettingUtils setAESKey:[data valueForKey:@"key"] lockName:[self getMacAddressFromAdvData:currentAdvData]];
                        
                        NSLog(@"key:%@,lockname:%@",[data valueForKey:@"key"],[NSString stringWithFormat:@"%@_%@",[currentAdvData objectForKey:@"kCBAdvDataLocalName"],[self getMacAddressFromAdvData:currentAdvData]]);
                        
                        //连接蓝牙
                        
                        [blueToothSDK stopScan];
                        [blueToothSDK connect:peripheral];
                        
                    }else{
                        
                        NSLog(@"绑定失败1");
                        [ProgressHUD dismiss];
                        
                        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"绑定失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                            
                        }];
                        [alertController addAction:cancelAction];
                        [self presentViewController:alertController animated:YES completion:nil];
                        
                    }
                    
                }else{
                
                    NSLog(@"绑定失败");
                    [ProgressHUD dismiss];
                    
                    
                    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"绑定失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                        
                    }];
                    [alertController addAction:cancelAction];
                    [self presentViewController:alertController animated:YES completion:nil];
                }
                
                
            });
            
        });

        
    }else if (bytes[1]==1) {
        
        //已设置密码
        
//        NSNumber * initialized = [((NSMutableDictionary*)[peripheralsSetPs objectAtIndex:indexPath.row]) valueForKey:@"initialized"];
//        if (!initialized.boolValue) {
//            
//            //说明获取密码失败
//            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"无法从服务器获取到对应锁的密码" message:nil preferredStyle:UIAlertControllerStyleAlert];
//            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//                
//            }];
//            [alertController addAction:cancelAction];
//            [self presentViewController:alertController animated:YES completion:nil];
//            return;
//        }
//        
//        
//        [self performSelector:@selector(connectTimeOut) withObject:nil afterDelay:10];
//        
//        //已经设置了密码，可以开锁
//        [ProgressHUD show:@"正在解锁..."];
//        NSLog(@"选择蓝牙：%@",[currentAdvData objectForKey:@"kCBAdvDataLocalName"]);
//        
//        [blueToothSDK stopScan];
//        [blueToothSDK connect:peripheral];
        
    }
    
}

-(void)connectTimeOut{
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"找不到设备" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
    }];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
    [ProgressHUD dismiss];
    [blueToothSDK scan];        //重新开始搜索蓝牙
    
}

-(NSString*)getMacAddressFromAdvData:(NSDictionary*)advertisementData
{
    NSString * macAddress = @"";
    
    NSData * strProtocol = [advertisementData objectForKey:@"kCBAdvDataManufacturerData"];
    Byte * bytes = strProtocol.bytes;
    Byte macBytes[6];
    [Utils arrayCopyWithSrc:bytes srcPos:6 dst:macBytes dstPos:0 length:6];
    NSMutableString * macBuffer = [[NSMutableString alloc]init];
    
//    for (int i = 0; i < 6; i ++) {
//        
//        [macBuffer appendFormat:@"%02x:",macBytes[i]];
//        
//    }
    for (int i = 5; i >= 0; i --) {
        
        [macBuffer appendFormat:@"%02x:",macBytes[i]];
        
    }
    if (macBuffer.length>0) {
        
        [macBuffer deleteCharactersInRange:NSMakeRange(macBuffer.length-1, 1)];
        macAddress = [macBuffer uppercaseString];
    }
    
    return macAddress;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/




//蓝牙搜索、连接相关回调
-(void)callbackPeripheralFound:(CBPeripheral *)peripheral RSSI:(NSNumber*)rssi lockName:(NSString*)lockName mac:(NSString*)mac advertisementData:(NSDictionary *)advertisementData
{

    NSString *advName = [advertisementData objectForKey:@"kCBAdvDataLocalName"];
    if (!(advName && advName.length>0)) {
        
        return;
        
    }
    
    NSData * strProtocol = [advertisementData objectForKey:@"kCBAdvDataManufacturerData"];
    Byte * bytes = strProtocol.bytes;
//    扫描回复数据的厂商自定义数据中包含锁控制模块是否已设置新秘钥的状态指示，如“07 ff d3 00” 中的 00 表示未设置新秘钥；“07 ff d3 01” 中的 01 表示已设置新秘钥。
     if(bytes[1]==1){
        
//         //已经设置密码，可以开锁
//         
//         dispatch_sync(dispatch_get_main_queue(), ^(void){
//             
//             if (peripheral.name && peripheral.name.length>0) {
//                 
//                 
//                 BOOL contain = NO;
//                 
//                 for (NSMutableDictionary * dictionary in peripheralsSetPs) {
//                     
//                     NSDictionary* advdata = [dictionary valueForKey:@"advertisementdata"];
//                     NSString * macAddressTmp = [self getMacAddressFromAdvData:advdata];
//                     if ([macAddressTmp isEqualToString:[self getMacAddressFromAdvData:advertisementData]]) {
//                         
//                         contain = YES;
//                         break;
//                         
//                     }
//                 }
//                 
//                 if (!contain) {
//                     
//                     NSMutableDictionary * dictionary = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:peripheral,advertisementData, [NSNumber numberWithBool:NO], nil] forKeys:[NSArray arrayWithObjects:@"peripheral" , @"advertisementdata", @"initialized",nil]];
//                     
//                     [peripheralsSetPs addObject:dictionary];
//                     [self.tableView reloadData];
//                     
//                     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
//                     dispatch_async(queue, ^(void){
//                         
//                         __block NSDictionary* responseDictionary;
//                         dispatch_sync(queue, ^(void){
//                             
//                             
//                             LMFlatformSDK * netSDK = [[LMFlatformSDK alloc]initWithCompanyID:@"1001"];
//                             responseDictionary = [netSDK requestLockKeyUserId:[SettingUtils getAccount] type:1 lockMacAddress:[self getMacAddressFromAdvData:advertisementData]];
//                             
//                         });
//                         
//                         dispatch_sync(dispatch_get_main_queue(), ^(void){
//                             
//                             if (responseDictionary) {
//                                 
//                                 NSNumber * code = (NSNumber*)[responseDictionary valueForKey:@"code"];
//                                 NSLog(@"code:%@",code);
//                                 if (code && code.intValue == 0) {
//                                     
//                                     //获取数据成功
//                                     NSDictionary * data = (NSDictionary*)[responseDictionary valueForKey:@"data"];
//                                     
//                                     NSDictionary* advdata = [dictionary valueForKey:@"advertisementdata"];
//                                     [SettingUtils setAESKey:[data valueForKey:@"key"] lockName:[NSString stringWithFormat:@"%@_%@",[advdata objectForKey:@"kCBAdvDataLocalName"],[self getMacAddressFromAdvData:advdata]]];
//                                     
//                                     NSLog(@"key:%@",[data valueForKey:@"key"]);
//                                     
//                                     for (NSMutableDictionary * dictionary in peripheralsSetPs) {
//                                         
//                                         //                                    CBPeripheral * peripheralTmp = [dictionary valueForKey:@"peripheral"];
//                                         //                                    if ([peripheralTmp.name isEqualToString:peripheral.name]) {
//                                         NSDictionary* advdata = [dictionary valueForKey:@"advertisementdata"];
//                                         NSString * macAddressTmp = [self getMacAddressFromAdvData:advdata];
//                                         if ([macAddressTmp isEqualToString:[self getMacAddressFromAdvData:advertisementData]]) {
//                                             
//                                             [dictionary setValue:[NSNumber numberWithBool:YES] forKey:@"initialized"];
//                                             
//                                             break;
//                                             
//                                         }
//                                     }
//                                     
//                                     [self.tableView reloadData];
//                                     
//                                 }else{
//                                     
//                                     NSLog(@"获取lockkey失败1");
//                                 }
//                                 
//                             }else{
//                                 
//                                 NSLog(@"获取lockkey失败");
//                             }
//                             
//                         });
//                     });
//                     
//                     
//                 }
//                 
//             }
//             
//         });
         
         return;
    }
    
    
    NSLog(@"peripheralFound:%@,name:%@,advname:%@,mac:%@",peripheral.name,lockName,[advertisementData objectForKey:@"kCBAdvDataLocalName"],mac);
    
    
    dispatch_sync(dispatch_get_main_queue(), ^(void){
        
        if (peripheral.name && peripheral.name.length>0) {
            
            
            BOOL contain = NO;
            
            for (NSMutableDictionary * dictionary in peripheralsNotSetPs) {
                
//                CBPeripheral * peripheralTmp = [dictionary valueForKey:@"peripheral"];
//                if ([peripheralTmp.name isEqualToString:peripheral.name]) {
                
                NSDictionary* advdata = [dictionary valueForKey:@"advertisementdata"];
                NSString * macAddressTmp = [self getMacAddressFromAdvData:advdata];
                if ([macAddressTmp isEqualToString:[self getMacAddressFromAdvData:advertisementData]]) {
                    
                    contain = YES;
                    break;
                    
                }
            }
            
            if (!contain) {
                
                NSMutableDictionary * dictionary = [NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:peripheral,advertisementData, [NSNumber numberWithBool:NO], nil] forKeys:[NSArray arrayWithObjects:@"peripheral" , @"advertisementdata", @"initialized",nil]];
                
                [peripheralsNotSetPs addObject:dictionary];
                [self.tableView reloadData];
                
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
                dispatch_async(queue, ^(void){
                    
                    __block NSDictionary* responseDictionary;
                    dispatch_sync(queue, ^(void){
                        
                        
                        LMFlatformSDK * netSDK = [[LMFlatformSDK alloc]initWithCompanyID:@"1001"];
                        responseDictionary = [netSDK requestLockKeyUserId:[SettingUtils getAccount] type:1 lockMacAddress:[self getMacAddressFromAdvData:advertisementData]];
                        
                        
                    });
                    
                    dispatch_sync(dispatch_get_main_queue(), ^(void){
                        
                        if (responseDictionary) {
                            
                            NSNumber * code = (NSNumber*)[responseDictionary valueForKey:@"code"];
                            NSLog(@"code:%@",code);
                            if (code && code.intValue == 0) {
                                
                                //获取数据成功
                                NSDictionary * data = (NSDictionary*)[responseDictionary valueForKey:@"data"];
                                
                                NSDictionary* advdata = [dictionary valueForKey:@"advertisementdata"];
                                [SettingUtils setAESKey:[data valueForKey:@"key"] lockName:[self getMacAddressFromAdvData:advdata]];
                                
                                NSLog(@"key:%@",[data valueForKey:@"key"]);
                                
                                for (NSMutableDictionary * dictionary in peripheralsNotSetPs) {
                                    
//                                    CBPeripheral * peripheralTmp = [dictionary valueForKey:@"peripheral"];
//                                    if ([peripheralTmp.name isEqualToString:peripheral.name]) {
                                    NSDictionary* advdata = [dictionary valueForKey:@"advertisementdata"];
                                    NSString * macAddressTmp = [self getMacAddressFromAdvData:advdata];
                                    if ([macAddressTmp isEqualToString:[self getMacAddressFromAdvData:advertisementData]]) {
                                    
                                        [dictionary setValue:[NSNumber numberWithBool:YES] forKey:@"initialized"];
                                        
                                        break;
                                        
                                    }
                                }
                                
                                [self.tableView reloadData];
                                
                            }else{
                                
                                NSLog(@"获取lockkey失败1");
                            }
                            
                        }else{
                            
                            NSLog(@"获取lockkey失败");
                        }
                        
                    });
                });
                
                
            }
            
        }
        
    });

}

-(void)callbackConnect:(CBPeripheral *)peripheral lockName:(NSString*)lockName
{
    
    dispatch_sync(dispatch_get_main_queue(), ^(void){
        
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(connectTimeOut) object:nil];
        
        
        //连接上蓝牙，
        NSLog(@"连接上lock:%@ , lockname:%@",peripheral.name,lockName);
        
        //    keyAdded = [[KeyModel alloc]init];
        //
        //    keyAdded.lockName = lockName;
        //    keyAdded.doorName = lockName;
        //
        //    [delegate.s addAdmin_advertisementData:currentAdvData];
        
        
        
        NSData * strProtocol = [currentAdvData objectForKey:@"kCBAdvDataManufacturerData"];
        Byte * bytes = strProtocol.bytes;
        if (bytes[1]==0) {
            
            //没有设置密码
            
            NSLog(@"设置密码：%@",[SettingUtils getAESKeylockName:[self getMacAddressFromAdvData:currentAdvData]]);
            [blueToothSDK setLockKey:[SettingUtils getAESKeylockName:[self getMacAddressFromAdvData:currentAdvData]]];
            
        }else if (bytes[1]==1) {
            
            //已经设置了密码，
            
            NSLog(@"选择蓝牙：%@",[currentAdvData objectForKey:@"kCBAdvDataLocalName"]);
            [blueToothSDK unlockWithKey:[self getMacAddressFromAdvData:currentAdvData]];
            
        }

        
    });
    
}

-(void)callbackDisconnect:(NSString*)lockName
{
    
    dispatch_sync(dispatch_get_main_queue(), ^(void){
        
        [ProgressHUD dismiss];
        [blueToothSDK scan];//重新开始搜索蓝牙
        [self.tableView reloadData];
        
    });
}


- (void)handleTextFieldTextDidChangeNotification:(NSNotification *)notification {
    
    UITextField *textField = notification.object;
    mLockNameInput = textField.text;
    
}

//操作回调

-(void)callbackSetLockKeyResult:(Byte)result
{
    dispatch_sync(dispatch_get_main_queue(), ^(void){
        
        NSLog(@"设置开锁密码完成：%0x",result);
        
        
        [ProgressHUD dismiss];
        
        if (result == 0) {
            
            //设置密码成功
            
//            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"设置开锁密码成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
//            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
//                
//                
//                
//            }];
//            [alertController addAction:cancelAction];
//            [self presentViewController:alertController animated:YES completion:nil];
            

            //进行一次开门动作
            [ProgressHUD show:@"设置锁密码成功，尝试开锁，请稍候..."];
            
            sleep(1);
            //直接开锁
            [blueToothSDK unlockWithKey:[SettingUtils getAESKeylockName:[self getMacAddressFromAdvData:currentAdvData]]];
            
            
        }else{
        
            //设置密码失败
            
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"设置开锁密码失败 ：%0x",result] message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:nil];
        }
        
//        [blueToothSDK disconnect:currentPeripheral];
        
//        [peripheralsSetPs removeAllObjects];
//        [peripheralsNotSetPs removeAllObjects];
//        [self.tableView reloadData];
    });
}



-(void)callbackUnlockResult:(Byte)result
{
    dispatch_sync(dispatch_get_main_queue(), ^(void){
        
        NSLog(@"开锁完成：%0x",result);
        [ProgressHUD dismiss];
        
        sleep(1);
        
        
        if (result == 0) {
            
            if (unlockWithMacAddress) {
                
                //不用修改名称，直接提示开锁成功
                
                UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"开锁成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
                
            }else{
                
                UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"开门成功，请修改锁名称。" message:nil preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");
                    
                }];
                
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                    
                    //身份认证
                    [ProgressHUD show:@"请稍候..."];
                    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
                    dispatch_async(queue, ^(void){
                        
                        __block NSDictionary* responseDictionary;
                        dispatch_sync(queue, ^(void){
                            
                            LMFlatformSDK * netSDK = [[LMFlatformSDK alloc]initWithCompanyID:@"1001"];
                            responseDictionary = [netSDK modifyLockName:mLockNameInput UserID:[SettingUtils getAccount] type:1 lockMacAddress:[self getMacAddressFromAdvData:currentAdvData]];
                            
                        });
                        
                        dispatch_sync(dispatch_get_main_queue(), ^(void){
                            
                            [ProgressHUD dismiss];
                            
                            [self getData];
                            
                            if (responseDictionary) {
                                
                                NSNumber * code = (NSNumber*)[responseDictionary valueForKey:@"code"];
                                
                                if (code && code.intValue == 0) {
                                    
                                    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"修改锁名称成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
                                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                                        
                                        
                                    }];
                                    
                                    [alertController addAction:cancelAction];
                                    [self presentViewController:alertController animated:YES completion:nil];
                                    
                                }else{
                                    
                                    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"修改锁名称失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
                                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                                        
                                    }];
                                    [alertController addAction:cancelAction];
                                    [self presentViewController:alertController animated:YES completion:nil];
                                }
                                
                            }else {
                                
                                UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"修改锁名称失败" message:nil preferredStyle:UIAlertControllerStyleAlert];
                                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                                    
                                }];
                                [alertController addAction:cancelAction];
                                [self presentViewController:alertController animated:YES completion:nil];
                            }
                            
                        });
                        
                    });
                    
                    
                }];
                
                [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
                    // 可以在这里对textfield进行定制，例如改变背景色
                    
                    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];
                    
                    
                }];
                
                
                [alertController addAction:cancelAction];
                [alertController addAction:okAction];
                
                [self presentViewController:alertController animated:YES completion:nil];
                
            }
            
        }else{
        
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"开锁失败，错误码：%0x",result] message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:nil];

            
        }
        
        
        [blueToothSDK disconnect:currentPeripheral];
        
        [peripheralsNotSetPs removeAllObjects];
        [self.tableView reloadData];
        
        
        unlockWithMacAddress = NO;
    });
}

-(void)callbackWithError:(PStoneErrorCode)errorCode desc:(NSString*)desc
{
    dispatch_sync(dispatch_get_main_queue(), ^(void){
        
        if (errorCode == PStoneErrorCode_NO_Peripheral) {
            
            NSLog(@"sdk返回错误码:%i",errorCode);
            [ProgressHUD dismiss];
            
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"sdk返回错误码:%i,描述：%@",errorCode,desc] message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                
            }];
            [alertController addAction:cancelAction];
            [self presentViewController:alertController animated:YES completion:nil];
            
        }
        
    });
    
    
}
//-(void)callbackSetupBlueTooth:(CBManagerState)state
//{
//
//    dispatch_sync(dispatch_get_main_queue(), ^(void){
//        
//        NSLog(@"反馈蓝牙状态:%i",state);
//        
//    });
//}

@end
